"use client";

import React, { useState, useEffect } from "react";
import { useAuth } from "@/contexts/auth-context";
import { Plus } from "lucide-react";
import { MoodService } from "@/services/mood.service";
import { AuthGuard } from "@/components/auth/auth-guard";
import { MoodCard } from "@/components/mood/MoodCard";
import { MoodEditModal } from "@/components/mood/MoodEditModal";
import { MoodCreateModal } from "@/components/mood/MoodCreateModal";
import type { Mood } from "@/services/mood.service";
import { MoodTrends } from "@/components/mood/MoodTrends";

export default function MoodPage() {
  const { user } = useAuth();
  const [moods, setMoods] = useState<Mood[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [isCreating, setIsCreating] = useState(false);
  const [editingMood, setEditingMood] = useState<Mood | null>(null);
  const [modalError, setModalError] = useState("");

  useEffect(() => {
    fetchMoods();
  }, []);

  async function fetchMoods() {
    try {
      const response = await MoodService.getMoods();
      if (response.status && response.data) {
        setMoods(Array.isArray(response.data) ? response.data : []);
      }
    } catch (error) {
      setError("获取心情记录失败");
      setMoods([]);
    } finally {
      setIsLoading(false);
    }
  }

  async function handleCreate(data: {
    mood: { level: 1 | 2 | 3 | 4 | 5 };
    remark: string;
  }) {
    try {
      const response = await MoodService.createMood({
        mood: data.mood,
        remark: data.remark
      });
      if (response.status && response.data) {
        setMoods([response.data, ...moods]);
        setIsCreating(false);
      }
    } catch (error) {
      setError("创建心情记录失败");
    }
  }

  async function handleUpdate(moodId: string) {
    try {
      if (!editingMood) return;
      const response = await MoodService.updateMood(moodId, editingMood);
      if (response.status && response.data) {
        setMoods(
          moods.map((m) => (m._id === moodId ? response.data : m)) as Mood[]
        );
        setEditingMood(null);
        setModalError("");
      } else {
        setModalError(response.message || "更新失败");
      }
    } catch (error) {
      setModalError(error instanceof Error ? error.message : "更新失败");
    }
  }

  async function handleDelete(moodId: string) {
    try {
      const response = await MoodService.deleteMood(moodId);
      if (response.status) {
        setMoods(moods.filter((m) => m._id !== moodId));
      }
    } catch (error) {
      setError("删除心情记录失败");
    }
  }

  return (
    <AuthGuard>
      <div className="container mx-auto py-8 px-4">
        {/* 页面标题和创建按钮 */}
        <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-12 gap-4">
          <div>
            <h1 className="text-4xl font-bold mb-2">心情记录</h1>
            <p className="text-muted-foreground">
              记录每一天的心情变化，追踪情绪轨迹
            </p>
          </div>
          <button
            onClick={() => setIsCreating(true)}
            className="flex items-center gap-2 bg-primary text-primary-foreground px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors md:self-start"
          >
            <Plus className="w-4 h-4" />
            新建记录
          </button>
        </div>

        {/* 添加心情趋势图表 */}
        <div className="mb-8">
          {isLoading ? (
            <div className="bg-card rounded-xl p-6 shadow-lg flex items-center justify-center h-[400px]">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            </div>
          ) : error ? (
            <div className="bg-card rounded-xl p-6 shadow-lg flex items-center justify-center h-[400px] text-destructive">
              {error}
            </div>
          ) : moods.length === 0 ? (
            <div className="bg-card rounded-xl p-6 shadow-lg flex items-center justify-center h-[400px] text-muted-foreground">
              暂无心情记录
            </div>
          ) : (
            <MoodTrends
              data={moods.slice(0, 30).reverse().map(mood => ({
                date: new Date(mood.createdAt).toISOString(),
                level: mood.mood.level
              }))}
            />
          )}
        </div>

        {/* 心情列表 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {isLoading ? (
            <div>加载中...</div>
          ) : error ? (
            <div className="text-destructive">{error}</div>
          ) : moods.length === 0 ? (
            <div className="text-muted-foreground">暂无心情记录</div>
          ) : (
            moods.map((mood) => (
              <MoodCard
                key={mood._id}
                mood={mood}
                onEdit={setEditingMood}
                onDelete={handleDelete}
              />
            ))
          )}
        </div>

        {/* 创建模态框 */}
        {isCreating && (
          <MoodCreateModal
            error={error}
            onClose={() => setIsCreating(false)}
            onSave={handleCreate}
          />
        )}

        {/* 编辑模态框 */}
        {editingMood && (
          <MoodEditModal
            mood={editingMood}
            error={modalError}
            onClose={() => {
              setEditingMood(null);
              setModalError("");
            }}
            onSave={(mood) => handleUpdate(mood._id)}
            onChange={setEditingMood}
          />
        )}
      </div>
    </AuthGuard>
  );
}
